//
//  RJCityWarningModel.m
//  AirQuality
//
//  Created by Po on 15/5/4.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJCityWarningModel.h"

@implementation RJCityWarningModel

- (void)setCitysFilePath:(NSString *)filePath
{
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].CityConnect data:@{} completeBlock:^(id responseObject) {
        NSArray * data = responseObject[@"DATA"];
        NSMutableArray * cityArray = [[NSMutableArray alloc] init];
        NSMutableArray * nameArray = [[NSMutableArray alloc] init];
        NSMutableArray * codeArray = [[NSMutableArray alloc] init];
        for (NSDictionary * dic in data) {
            NSString * string = dic[@"CITYNAME"];
            NSRange range = [string rangeOfString:@"市"];
            if (range.location == NSNotFound) {
                range = [string rangeOfString:@"县"];
            }
            string = [string substringToIndex:range.location];
            [nameArray addObject:string];
            [codeArray addObject:dic[@"CITYCODE"]];
            [cityArray addObject:@{dic[@"CITYCODE"]:string}];
        }
        _cityNames = [NSArray arrayWithArray:nameArray];
        _cityCodes = [NSArray arrayWithArray:codeArray];
        [cityArray writeToFile:filePath atomically:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WarningGetAllCitys" object:@{@"citys":cityArray}];
    } failBlack:^(id response) {
        
    }];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _warningUserData = [[NSMutableDictionary alloc] init];
        _checkUserData = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)setWarningData:(NSDictionary *)data
{
    _warningPM25PageData = [[NSMutableArray alloc] init];
    _warningAQIPageData = [[NSMutableArray alloc] init];
    _warningFirstPageData = [[NSMutableArray alloc] init];
    
    [RJUserData defaultRJUserData].isDone = [data[@"isDone"] boolValue];
    [RJUserData defaultRJUserData].isAudit = [data[@"isAudit"] boolValue];
    [RJUserData defaultRJUserData].isHistory = [data[@"hasHistory"] boolValue];
    _mAQI = data[@"m_aqi"];
    _mPM25 = data[@"m_pm2_5"];
    _mPP = data[@"m_pp"];
    
    //初始化页面数据
    [_warningPM25PageData addObject:_mPM25];
    [_warningAQIPageData addObject:_mAQI];
    [_warningFirstPageData addObject:_mPP];
    NSDictionary * dataDic;
    NSString * historyTime;
    
    BOOL isDone = [data[@"isDone"] boolValue];
    BOOL hasHistory = [data[@"hasHistory"] boolValue];
    
    if (isDone || hasHistory) {
        if (isDone) {
            dataDic = data[@"forecast"];
        } else{
            dataDic = data[@"history"];
            historyTime = dataDic[@"TIMEPOINT"];
        }
        _warningPM25 = dataDic[@"PM2_5"];
        _warningPM25DR = dataDic[@"PM2_5_DR"];
        _warningPM25IR = dataDic[@"PM2_5_IR"];
        _warningAQICenter = dataDic[@"AQI_NPO"];
        _warningAQIRange = dataDic[@"AQI"];
        _warningFirstPollutions = dataDic[@"PRIMARYPOLLUTANT"];
        _warningQuality = dataDic[@"QUALITY"];
        //更新页面数据
        if (!isDone && hasHistory) {
            [self updateWarningDataHistoryWithDay:historyTime];
        }
        _warningUserData = [NSMutableDictionary dictionaryWithDictionary:@{
                                                                           @"aqi":_warningAQIRange,
                                                                           @"aqi_npo":_warningAQICenter,      @"quality":_warningQuality,                      @"pm2_5":_warningPM25, @"pm2_5_dr":_warningPM25DR,                    @"pm2_5_ir":_warningPM25IR,@"primaryPollutant":_warningFirstPollutions
                                                                           }];
        [_warningPM25PageData addObjectsFromArray:@[_warningPM25,_warningPM25DR,_warningPM25IR]];
        [_warningAQIPageData addObjectsFromArray:@[_warningAQICenter,_warningAQIRange,_warningQuality]];
        [_warningFirstPageData addObject:_warningFirstPollutions];
    }
}

- (void)setCheckData:(NSDictionary *)data
{
    _checkPM25PageData = [[NSMutableArray alloc] init];
    _checkAQIPageData = [[NSMutableArray alloc] init];
    _checkFirstPageData = [[NSMutableArray alloc] init];
    
    [RJUserData defaultRJUserData].isDone = [data[@"isDone"] boolValue];
    [RJUserData defaultRJUserData].isAudit = [data[@"isAudit"] boolValue];
    [RJUserData defaultRJUserData].isHistory = [data[@"hasHistory"] boolValue];
    
    if ([RJUserData defaultRJUserData].isDone || [RJUserData defaultRJUserData].isAudit) {
        NSDictionary * forescastsDic = data[@"forecasts"][0];
        NSArray * checkPM25 = data[@"expertSet"][@"PM2_5"];
        _checkAQI = @[@[forescastsDic[@"AQI"]],@[]];
        
        _checkUserData = [NSMutableDictionary dictionaryWithDictionary:@{
                                                                         @"primaryPollutant_audit":@[],
                                                                         @"quality_audit":@[],
                                                                         @"message":@[],
                                                                         @"aqi_npo":@[],
                                                                         @"aqi_audit":@[],
                                                                         @"aqi":@[],
                                                                         @"aqi_range":@[]
                                                                         }];
        
        //数据更新
        [_checkPM25PageData addObjectsFromArray:@[checkPM25,data[@"forecasts"]]];
        [_checkAQIPageData addObjectsFromArray:@[data[@"forecasts"]]];
        [_checkFirstPageData addObjectsFromArray:@[data[@"forecasts"]]];
        
        if ([RJUserData defaultRJUserData].isAudit) {
            NSDictionary * audit = data[@"audit"];
            _checkFirstPollutions = audit[@"PRIMARYPOLLUTANT"];
            _checkRank = audit[@"QUALITY"];
            _checkFirstPageData = [NSMutableArray arrayWithArray:@[data[@"forecasts"],_checkFirstPollutions,_checkRank]];
            
            NSDictionary * expert = data[@"expertSet"];
            _checkExpertAQI = expert[@"AQI"];
            _checkExpertAQINPO = expert[@"AQI_NPO"];
            _checkExpertAQIPO = expert[@"AQI_PO"];
            _checkAuditAQI = audit[@"AQI"];
            [_checkAQIPageData addObjectsFromArray:@[_checkExpertAQI, _checkExpertAQINPO,_checkAuditAQI,_checkExpertAQIPO]];
        }
    }
}

- (NSDictionary *)getAllWarningData
{
    NSMutableDictionary * data = [NSMutableDictionary dictionary];
    //获取上传格式
    NSArray * userDataKeys = [_warningUserData allKeys];
    for (NSUInteger i = 0; i < _warningUserData.count; i ++) {
        NSArray * tempData = [_warningUserData objectForKey:userDataKeys[i]];
        [data setObject:[self getStringWithDataArray:tempData] forKey:userDataKeys[i]];
    }
    //添加固定数据
    [data addEntriesFromDictionary:@{
                                     @"timepoint":[NSData data],
                                     @"cityCode":_currentCityCode,
                                     @"o3":@"||||",
                                     @"o3_dr":@"||||",
                                     @"o3_ir":@"||||",
                                     @"pm2_5Content":@"",
                                     @"o3Content":@"",
                                     @"aqiContent":@"",
                                     @"aqi_po":@"||||",
                                     @"primaryPollutantContent":@""
                                     }];
    return data;
}

- (NSDictionary *)getAllCheckData
{
    NSMutableDictionary * data = [NSMutableDictionary dictionary];
    //获取上传格式
    NSArray * userDataKeys = [_checkUserData allKeys];
    for (NSUInteger i = 0; i < _checkUserData.count; i ++) {
        if ([userDataKeys[i] isEqualToString:@"message"]) {
            [data setObject:_checkUserData[@"message"] forKey:userDataKeys[i]];
            continue;
        }
        NSArray * tempData = [_checkUserData objectForKey:userDataKeys[i]];
        NSLog(@"%@",userDataKeys[i]);
        [data setObject:[self getStringWithDataArray:tempData] forKey:userDataKeys[i]];
    }
    //添加固定数据
    [data addEntriesFromDictionary:@{
                                     @"timePoint":_timepoint,
                                     @"cityCode":_currentCityCode,
                                     @"o3_dr":@"||||",
                                     @"o3_ir":@"||||",
                                     @"content_audit":@"",
                                     @"aqi_po":@"||||",
                                     @"aqiContent":@"",
                                     @"aqiContent_audit":@"",
                                     @"primaryPollutantContent_audit":@"",
                                     }];
    return data;
}

#pragma mark - 辅助方法
//更新当天历史记录（除去已经失效的历史记录）
- (void)updateWarningDataHistoryWithDay:(NSString *)time
{
    NSString * historyTime = [time substringToIndex:10];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSUInteger passDayNum = [RJTools getDayWithStartDay:[formatter dateFromString:historyTime] endDay:[NSDate date]];
    _warningPM25 = [self getTrueHistory:_warningPM25 dayNum:passDayNum];
    _warningPM25DR = [self getTrueHistory:_warningPM25DR dayNum:passDayNum];
    _warningPM25IR = [self getTrueHistory:_warningPM25IR dayNum:passDayNum];
    _warningAQICenter = [self getTrueHistory:_warningAQICenter dayNum:passDayNum];
    _warningAQIRange = [self getTrueHistory:_warningAQIRange dayNum:passDayNum];
    _warningFirstPollutions = [self getTrueHistory:_warningFirstPollutions dayNum:passDayNum];
    _warningQuality = [self getTrueHistory:_warningQuality dayNum:passDayNum];
}

//根据历史记录来获得当天的历史信息
- (NSArray *)getTrueHistory:(NSArray *)data dayNum:(NSUInteger)daynum
{
    if (daynum > 5) {
        daynum = 5;
    }
    NSMutableArray * temp = [[data subarrayWithRange:NSMakeRange(daynum, data.count - daynum)] mutableCopy];
    for (NSUInteger i = 0; i < daynum; i ++) {
        [temp addObject:@""];
    }
    return temp;
}

- (BOOL)checkWarningUserDataCompletion
{
    if (_warningUserData.count != 7) {
        return NO;
    }
    for (NSArray * data in [_warningUserData allValues]) {
        if (![self checkDataWithArray:data]) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)checkCheckUserDataCompletion
{
    if (_checkUserData.count != 9) {
        return NO;
    }
    
    NSArray * allKeys = [_checkUserData allKeys];
    for (NSString * key in allKeys) {
        if ([key isEqualToString:@"message"]) {
            continue;
        }
        
        NSArray * data = _checkUserData[key];
        if ([key isEqualToString:@"aqi_range"] || [key isEqualToString:@"aqi_npo"]) {
            if (![self checkDataWithArray:_checkUserData[@"aqi_range"]] && ![self checkDataWithArray:_checkUserData[@"aqi_npo"]]) {
                return NO;
            }
        } else if (![self checkDataWithArray:data]) {
            return NO;
        }
    }
    return YES;
}

/**检测一项数据的完整性*/
- (BOOL)checkDataWithArray:(NSArray *)data
{
    //判断是否有数据
    if (!data) {
        return NO;
    }
    
    for (NSUInteger i = 0; i < data.count; i ++) {
        if (i < 3) {
            if ([data[i] isEqualToString:@""]) {
                return NO;
            }
            
            NSRange range = [data[i] rangeOfString:@"~"];
            if (range.location != NSNotFound) {
                if ([data[i] isEqualToString:@"~"]) {
                    return NO;
                } else {
                    NSArray * array = [data[i] componentsSeparatedByString:@"~"];
                    if ([array[0] isEqualToString:@""] || [array[1] isEqualToString:@""]) {
                        return NO;
                    }
                }
            }
        }
    }
    return YES;
}

/**转化一项数据为上传的字符串*/
- (NSString *)getStringWithDataArray:(NSArray *)data
{
    NSMutableString * temp = [[NSMutableString alloc] init];
    for (NSUInteger i = 0; i < 5; i ++) {
        if (i < 3) {
            [temp appendFormat:@"%@%@", data[i],@"|"];
        } else {
            [temp appendFormat:@"%@", (i == 4 ? @"" : @"|")];
        }
    }
    return temp;
}



/**区间字符串相加*/
- (NSString *)getRangeWithFirstString:(NSString *)string1 secondString:(NSString *)string2
{
    NSArray * string1Array = [string1 componentsSeparatedByString:@"~"];
    NSArray * string2Array = [string2 componentsSeparatedByString:@"~"];
    NSArray * tempArray = @[
                            @([string1Array[0] integerValue] + [string2Array[0] integerValue]),
                            @([string1Array[1] integerValue] + [string2Array[1] integerValue])
                            ];
    return [tempArray componentsJoinedByString:@"~"];
}


@end
